<?php

require_once('./inc/data/dbparam.php');
require_once('./inc/data/dbfunc.php');
// require_once('./inc/func/jwt.php');
require_once('./inc/func/utils.php');
header('Content-Type: json');

$conn = conn_mysql();

$role = $_POST['role'];
$uid = $_POST['uid'];




// $role = '0';
// $uid = '2003010211';
// $upwd = 'e10adc3949ba59abbe56e057f20f883e';

// $role为'0'是学生, '1'是老师
if ($role == '0'){
    // 查询盐字段
    $query_salt = "
    select 
        salt 
    from
        huangcz_stu 
    where
        stu_id = '{$uid}'
    ";
    $res = $conn->query($query_salt);
    $row = $res->fetch_assoc();
    // 盐字段为空返回失败状态码
    if (!$row){
        exit(json_encode([
            'status' => 0
        ]));
    }
    $arr = explode(',', $row['salt']);
    $upwd = checkPwd($arr[0], $arr[1], trim($_POST['upwd']));

    $sql = '
        select stu_id, stu_name, dep_name, stu_img
        from huangcz_stu, huangcz_class, huangcz_major, huangcz_dep
        where cl_major = ma_id
        and ma_dep = dep_id
        and stu_id = ?
        and stu_pwd = ?;
    ';
}else{
    // 查询盐字段
    $query_salt = "
    select 
        salt 
    from
        huangcz_te
    where
        te_id = '{$uid}'
    ";
    $res = $conn->query($query_salt);
    $row = $res->fetch_assoc();
    // 盐字段为空返回失败状态码
    if (!$row){
        exit(json_encode([
            'status' => 0
        ]));
    }
    $arr = explode(',', $row['salt']);
    $upwd = checkPwd($arr[0], $arr[1], trim($_POST['upwd']));

    $sql = '
        select te_id, te_name, dep_name, te_img
        from huangcz_te, huangcz_dep
        where te_dep = dep_id
        and te_id = ?
        and te_pwd = ?;
    ';
}

$stmt = $conn->prepare($sql);
$stmt->bind_param('is', $uid, $upwd);
$stmt->bind_result($uid, $uname, $udep, $uimg);
$stmt->execute();

if ($stmt->fetch()){
    // $token = Token::get_token($uid, time()+60*60*24);
    session_start();
    $_SESSION['uName'] = $uname;
    $_SESSION['uId'] = $uid;
    $_SESSION['uDep'] = $udep;
    $_SESSION['role'] = $role;
    if ($uimg == 'te.jpg') $_SESSION['uImg'] = '/TeacherStuSys/inc/pic/icon/te.jpg';
    else if ($uimg == 'stu.jpg') $_SESSION['uImg'] = '/TeacherStuSys/inc/pic/icon/stu.jpg';
    else $_SESSION['uImg'] = "/TeacherStuSys/inc/portrait/$uimg";
    session_commit();
    // setcookie('auth', $token, time()+60*60*24);
    setcookie('uName', $uname, 0, '/TeacherStuSys');
    setcookie('uId', $uid, 0, '/TeacherStuSys');
    setcookie('uDep', $udep, 0, '/TeacherStuSys');
    setcookie('role', $role, 0, '/TeacherStuSys');
    setcookie('uImg', $_SESSION['uImg'], 0, '/TeacherStuSys');
    exit(json_encode([
        'status' => 1,
        'uname' => $uname
    ],JSON_UNESCAPED_UNICODE));
}else{
    exit(json_encode([
        'status' => 0
    ]));
}



